package com.uusee.crawler.dbwriter;

import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.uusee.crawler.framework.Processor;
import com.uusee.crawler.model.CrawlURI;
import com.uusee.framework.bo.UniversalBo;
import com.uusee.framework.util.query.CriteriaInfo;
import com.uusee.shipshape.bk.model.Baike;
import com.uusee.shipshape.bk.model.Episode;

public class EpisodeDbWriter extends Processor {
	private static Log log = LogFactory.getLog(EpisodeDbWriter.class);
	private UniversalBo universalBo;

	public void setUniversalBo(UniversalBo universalBo) {
		this.universalBo = universalBo;
	}

	protected void innerProcess(CrawlURI crawlURI) {
		Episode episode = (Episode) crawlURI.getModel();
		Baike baike = episode.getBaike();
		try {
			baike = getBaikeByOriIdAndSourceSite(baike);
			episode.setBaike(baike);
			Episode oldepisode = getOldEpisode(episode);
			if (oldepisode!=null) {
				oldepisode.setName(episode.getName());
				oldepisode.setSeason(episode.getSeason());
				oldepisode.setVolumn(episode.getVolumn());
				oldepisode.setSummary(episode.getSummary());
				oldepisode.setUpdateUser(episode.getUpdateUser());
				oldepisode.setUpdateDate(episode.getUpdateDate());
				universalBo.doUpdate(episode);
				log.info(baike.getOriId() + "-更新百科分集介绍,"+oldepisode.getName2()+";季:"+oldepisode.getSeason()+";集:"+oldepisode.getVolumn());
			} else {
				universalBo.doSave(episode);
				log.info(baike.getOriId() + "-增加百科分集介绍,"+episode.getName2()+";季:"+episode.getSeason()+";集:"+episode.getVolumn());
			}
			baike.setUpdateDate(new Date());
			baike.setOther4("抓取更新剧情。");
			universalBo.doUpdate(baike);
		} catch (Exception e) {
			log.error(e.getMessage());
			log.error(baike.getOriId() + "-增加百科分集介绍,DB时发生错误。", e);
		}
	}

	private boolean isExist(Episode e) {
		CriteriaInfo ci = new CriteriaInfo();
		ci.eq("baike", e.getBaike());
		ci.eq("name2", e.getName2());
		int count = universalBo.getCountByCriteriaInfo(Episode.class, ci);
		if (count > 0) {
			return true;
		} else {
			return false;
		}
	}
	
	private Episode getOldEpisode(Episode e) {
		CriteriaInfo ci = new CriteriaInfo();
		ci.eq("baike", e.getBaike());
		ci.eq("name2", e.getName2());
		List<Episode> episodeList = universalBo.getEntitiesByCriteriaInfo(Episode.class, ci);
		if (episodeList.size() > 0) {
			return episodeList.get(0);
		} else {
			return null;
		}
	}

	private Baike getBaikeByOriIdAndSourceSite(Baike baike) {
		Baike oldBaike = null;
		String oriId = baike.getOriId();
		String sourceSite = baike.getSourceSite();

		CriteriaInfo ci = new CriteriaInfo();
		ci.eq("sourceSite", sourceSite);
		ci.eq("oriId", oriId);
		List<Baike> baikeList = universalBo.getEntitiesByCriteriaInfo(Baike.class, ci);
		if (baikeList != null && baikeList.size() == 1) {
			oldBaike = baikeList.get(0);
		}
		return oldBaike;
	}
}
